package sz.szsmk.citizencard.ui.dzsmkavtivity;


import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.chenenyu.router.annotation.Route;

import java.util.ArrayList;
import java.util.List;

import sz.szsmk.citizencard.DaggerApplication;
import sz.szsmk.citizencard.R;
import sz.szsmk.citizencard.databinding.ActivityFirstRechargeBinding;
import sz.szsmk.citizencard.db.DaoSession;
import sz.szsmk.citizencard.db.SysConfDao;
import sz.szsmk.citizencard.ioc.Compontent.DaggerCommonActivityComponent;
import sz.szsmk.citizencard.model.network.dzbean.res.BankCard;
import sz.szsmk.citizencard.model.network.dzbean.res.CheckPsdRes;
import sz.szsmk.citizencard.model.network.dzbean.res.PreAuthResult;
import sz.szsmk.citizencard.model.network.dzbean.res.SysConf;
import sz.szsmk.citizencard.mvp.contract.IFirstRechargeContact;
import sz.szsmk.citizencard.mvp.dzsmkpresenter.FirstRechargePresenter;
import sz.szsmk.citizencard.ui.base.IBaseActivity;
import sz.szsmk.citizencard.util.ACache;
import sz.szsmk.citizencard.util.Constant;
import sz.szsmk.citizencard.util.JumpUtils;
import sz.szsmk.citizencard.util.PubUtils;
import sz.szsmk.citizencard.widget.GlobalVariables;
import sz.szsmk.citizencard.widget.PayPsdInputView;

/**
 * Copyright (c)2018
 * author: zhf
 * created on: 2018/9/6 19:57
 * description:
 */
@Route("firstrecharge")
public class FirstRechargeActivity extends IBaseActivity<FirstRechargePresenter, ActivityFirstRechargeBinding>
        implements IFirstRechargeContact.IFirstRechargeView {

    TextView trustCardTxt;
    //    是否是选择器操作
    private boolean isSelectorAction = false;
    private String token;
    private String openId;
    private String channelId;
    private SysConf sysConf;
    private String money;
    private PopupWindow popupWindow;
    private PopupWindow popResult;
    private BankCard bankCard;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        trustCardTxt = findViewById(R.id.trust_card_txt);
    }

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_first_recharge;
    }

    @Override
    protected void initInjector() {

        DaggerCommonActivityComponent.builder().appCompontent(DaggerApplication.getAppComponent())
                .build().inject(this);
    }

    @Override
    protected void initViews() {



        DaoSession daoSession = DaggerApplication.getmDaoSession();
        SysConfDao sysConfDao = daoSession.getSysConfDao();
        List<SysConf> sysConfs = sysConfDao.loadAll();
        if (null != sysConfs && sysConfs.size() > 0) {
            sysConf = sysConfs.get(0);
        }

        mPresenter.gainMyBankCard();
        token = ACache.get(this).getAsString("token");
        openId = ACache.get(this).getAsString("openId");
        channelId = ACache.get(this).getAsString("channelId");
        dataBinding.nextBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mPresenter.checkPwdSetting(openId, channelId, token, view);

            }
        });

        dataBinding.back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finishView();
            }
        });
        dataBinding.deleteRecharge.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dataBinding.rechargeMoney.setText("");

            }
        });
        dataBinding.rechargeMoney.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (charSequence.length() == 0)
                    dataBinding.deleteRecharge.setVisibility(View.GONE);
                else
                    dataBinding.deleteRecharge.setVisibility(View.VISIBLE);

//                清除选择器的选择
                if (isSelectorAction)
                    dataBinding.quickSelector.clearCheck();
                else
                    isSelectorAction = false;
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        dataBinding.quickSelector.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
//                isSelectorAction = true;
                int checkedRadioButtonId = radioGroup.getCheckedRadioButtonId();
                if (checkedRadioButtonId == R.id.money_10) {
                    dataBinding.rechargeMoney.setText("10");
//                        dataBinding.rechargeMoney.setTextColor(getResources().getColor(R.color.white));
                } else if (checkedRadioButtonId == R.id.money_50) {
                    dataBinding.rechargeMoney.setText("50");
//                        dataBinding.money10.setChecked(false);
                } else if (checkedRadioButtonId == R.id.money_100) {
                    dataBinding.rechargeMoney.setText("100");
                } else if (checkedRadioButtonId == R.id.money_200) {
                    dataBinding.rechargeMoney.setText("200");
                }
                dataBinding.rechargeMoney.setSelection(dataBinding.rechargeMoney.getText().toString().length());
            }
        });
    }

    @Override
    protected void updateViews() {

    }

    @Override
    public void chargeMoneyFail() {
        dismissLoadingDialog();
        Toast.makeText(this, "充值失败", Toast.LENGTH_SHORT).show();
        showResult(false);
    }

    @Override
    public void onBackPressed() {
        finishView();

//        super.onBackPressed();
    }

    private void finishView() {
        if (BindCashCardActivity.instance != null) {
            BindCashCardActivity.instance.finish();
        }
        if (SignUpElectronCardActivity.instance != null) {

            SignUpElectronCardActivity.instance.finish();
        }
        if (AppendRealNameInfoActivity.instance != null) {

            AppendRealNameInfoActivity.instance.finish();
        }
        finish();

    }

    @Override
    public void chargeMoneySucc() {
        PreAuthResult preAuthResult = GlobalVariables.getInstance(this).getPreAuthResult();
        preAuthResult.setUserStatus(Constant.QUERY_QR_RESULT_AUTHED);
        GlobalVariables.getInstance(this).setPreAuthResult(this, preAuthResult);
        dismissLoadingDialog();
        showResult(true);
    }

    private void showResult(final boolean success) {
        View popView = getLayoutInflater().inflate(R.layout.qr_pop_recharge_result, null);
        TextView tv_qr_ok = (TextView) popView.findViewById(R.id.tv_qr_ok);
        ImageView iv_qr_recharge_status = (ImageView) popView.findViewById(R.id.iv_qr_recharge_status);
        TextView tv_qr_recharge_message = (TextView) popView.findViewById(R.id.tv_qr_recharge_message);
        TextView tv_qr_recharge_tip = (TextView) popView.findViewById(R.id.tv_qr_recharge_tip);
        if (success) {
            iv_qr_recharge_status.setImageResource(R.drawable.qr_recharge_success);
            tv_qr_recharge_message.setText("充值成功");
            tv_qr_recharge_tip.setVisibility(View.VISIBLE);
        } else {
            iv_qr_recharge_status.setImageResource(R.drawable.qr_recharge_failed);
            tv_qr_recharge_message.setText("充值失败");
            tv_qr_recharge_tip.setVisibility(View.GONE);
        }
        popResult = new PopupWindow(popView,
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);//popView即popupWindow的布局，ture设置focusAble.

        //必须设置BackgroundDrawable后setOutsideTouchable(true)才会有效。这里在XML中定义背景，所以这里设置为null;
//        popupWindow.setBackgroundDrawable(new BitmapDrawable(getResources(), (Bitmap) null));
//        popupWindow.setOutsideTouchable(false); //点击外部关闭。
        popResult.setAnimationStyle(android.R.style.Animation_Dialog);    //设置一个动画。
        backgroundAlpha(0.5f);
        popResult.showAtLocation(findViewById(R.id.first_ll), Gravity.CENTER, 0, 0);
        tv_qr_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                popResult.dismiss();
                if (success) {
                    JumpUtils.jump(FirstRechargeActivity.this, "dzsmk", 0);
                    finish();
                }
            }
        });
        popResult.setOnDismissListener(new poponDismissListener());
    }

    @Override
    public void checkPwdSettingSucc(CheckPsdRes ibaseBean, View view) {
        String isSettingPwd = ibaseBean.getData().getIsSettingPwd();
        if (isSettingPwd.equals("0")) {
            Intent intent = new Intent(this, PayPwdSetActivity.class);
            intent.putExtra("type", true);
            startActivity(intent);
        } else {

//            mPresenter.chargeMoney();

            money = dataBinding.rechargeMoney.getText().toString();
            if (TextUtils.isEmpty(money)) {
                showTipDialog("请输入充值金额");
            } else if (sysConf != null && Integer.parseInt(money) * 100 < sysConf.getRechargeFee()) {
                showTipDialog("单次充值金额不能小于" + (sysConf.getRechargeFee() / 100) + "元");
            } else {
                showPassword(view);
            }


        }
    }

    private void showTipDialog(String tip) {
        PubUtils.popTipOrWarn(this, tip);
    }

    private void showPassword(View view) {
        View popView = getLayoutInflater().inflate(
                R.layout.qr_pop_password, null);
        final PayPsdInputView payPsdInputView = (PayPsdInputView) popView.findViewById(R.id.password);
        TextView tv_qr_cancel = (TextView) popView.findViewById(R.id.tv_qr_cancel);
        TextView tv_qr_ok = (TextView) popView.findViewById(R.id.tv_qr_ok);
        popupWindow = new PopupWindow(popView,
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);//popView即popupWindow的布局，ture设置focusAble.
        popupWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
        popupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        //必须设置BackgroundDrawable后setOutsideTouchable(true)才会有效。这里在XML中定义背景，所以这里设置为null;
//        popupWindow.setBackgroundDrawable(new BitmapDrawable(getResources(), (Bitmap) null));
//        popupWindow.setOutsideTouchable(true); //点击外部关闭。
        popupWindow.setAnimationStyle(android.R.style.Animation_Dialog);    //设置一个动画。
        backgroundAlpha(0.5f);
        //设置Gravity，让它显示在右上角。

        popupWindow.showAtLocation(view, Gravity.BOTTOM, 0, 0);


        tv_qr_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });

        tv_qr_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String password = payPsdInputView.getPasswordString();
                if (password.length() < 6) {
                    showTipDialog("密码位数不全");
                } else {
                    popupWindow.dismiss();
                    showLoadingDialog();
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                    mPresenter.checkPayPassword(password, openId, token, channelId);
                }
            }
        });

        popupWindow.setOnDismissListener(new poponDismissListener());
    }

    private void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        getWindow().setAttributes(lp);
    }



    class poponDismissListener implements PopupWindow.OnDismissListener {

        @Override
        public void onDismiss() {
            //Log.v("List_noteTypeActivity:", "我是关闭事件");
            backgroundAlpha(1f);
        }
    }

    @Override
    public void checkPwdSettingFail() {

//        mPresenter.chargeMoney();
    }

    @Override
    public void checkPayPasswordFail() {
        dismissLoadingDialog();
    }

    @Override
    public void checkPayPasswordSucc() {
        String bankCardId = bankCard.getBankCardId();
        mPresenter.chargeMoney(Integer.parseInt(money) * 100, bankCardId);
    }

    @Override
    public void gainMyBankCardFail() {

    }

    @Override
    public void gainMyBankCardSucc(ArrayList<BankCard> list) {
        bankCard = list.get(0);
        trustCardTxt.setText(bankCard.getBankName());
    }
}
